import { FormControl, FormLabel, Tooltip } from '@chakra-ui/react';
import { Select, SelectProps } from '@mantine/core';

import { memo, RefObject, useCallback, useState } from 'react';
import { useMantineSelectStyles } from '@tourfly/theme';

export type IAISelectDataType = {
  value: string;
  label: string;
  tooltip?: string;
};

type IAISelectProps = Omit<SelectProps, 'label'> & {
  tooltip?: string;
  label?: string;
  inputRef?: RefObject<HTMLInputElement>;
};

const IAIMantineSearchableSelect = (props: IAISelectProps) => {
  const {
    searchable = true,
    tooltip,
    inputRef,
    onChange,
    label,
    disabled,
    ...rest
  } = props;

  const [searchValue, setSearchValue] = useState('');

  // wrap onChange to clear search value on select
  const handleChange = useCallback(
    (v: string | null) => {
      setSearchValue('');

      if (!onChange) {
        return;
      }

      onChange(v);
    },
    [onChange]
  );

  const styles = useMantineSelectStyles();

  return (
    <Tooltip label={tooltip} placement="top" hasArrow>
      <Select
        ref={inputRef}
        label={
          label ? (
            <FormControl isDisabled={disabled}>
              <FormLabel>{label}</FormLabel>
            </FormControl>
          ) : undefined
        }
        disabled={disabled}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        onChange={handleChange}
        searchable={searchable}
        maxDropdownHeight={300}
        styles={styles}
        size="xs"
        {...rest}
      />
    </Tooltip>
  );
};

export default memo(IAIMantineSearchableSelect);
